package com.demon.androidbasic.base

import android.content.Context
import android.content.Intent
import android.content.res.Resources
import android.os.Bundle
import android.view.KeyEvent
import androidx.annotation.CallSuper
import androidx.annotation.ColorRes
import androidx.annotation.StringRes
import androidx.viewbinding.ViewBinding

import com.blankj.utilcode.util.ThreadUtils
import com.blankj.utilcode.util.TimeUtils
import com.demon.androidbasic.BaseApplication
import com.demon.androidbasic.DisplayUtil
import com.demon.androidbasic.R
import com.demon.androidbasic.action.SwipeAction
import com.demon.androidbasic.action.TitleBarAction
import com.demon.androidbasic.constant.Constant
import com.demon.androidbasic.dialog.BaseDialog
import com.demon.androidbasic.dialog.WaitDialog
import com.demon.net.AppResponse
import com.demon.net.RpcCallManager
import com.gyf.immersionbar.ImmersionBar
import com.gyf.immersionbar.ktx.setFitsSystemWindows
import com.hjq.bar.TitleBar
import com.hjq.http.listener.OnHttpListener
import io.reactivex.Flowable
import io.reactivex.subscribers.ResourceSubscriber
import okhttp3.Call


/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2018/10/18
 * desc   : 项目中的 Activity 基类
 */
abstract class MyActivity<T : ViewBinding> : BaseBindActivity<T>(), TitleBarAction, SwipeAction, RpcCallManager {

    private lateinit var rpcCallManager: RpcCallManager

    /**
     * 标题栏对象
     */
    private var mTitleBar: TitleBar? = null

    /**
     * 状态栏沉浸
     */
    private var mImmersionBar: ImmersionBar? = null

    /**
     * 加载对话框
     */
    private var mDialog: BaseDialog? = null

    /**
     * 对话框数量
     */
    private var mDialogTotal = 0

    /**
     * 当前加载对话框是否在显示中
     */
    val isShowDialog: Boolean
        get() = mDialog != null && mDialog!!.isShowing

    /**
     * 显示加载对话框
     */
    fun showDialog(msg: String? = null) {
        mDialogTotal++
        postDelayed({

            if (mDialogTotal > 0 && !isFinishing) {
                if (mDialog == null) {
                    val builder = WaitDialog.Builder(this).setCancelable(false)
                    if (!msg.isNullOrEmpty()) {
                        builder.setMessage(msg)
                    } else {
                        builder.setMessage(R.string.common_loading)
                    }
                    mDialog = builder.create()
                }
                if (!mDialog!!.isShowing) {
                    mDialog!!.show()
                }
            }
        }, 300)
    }

    /**
     * 隐藏加载对话框
     */
    fun hideDialog() {

        if (mDialogTotal > 0) {
            mDialogTotal--
        }

        if (mDialogTotal == 0 && mDialog != null && mDialog?.isShowing == true && !isFinishing) {
            mDialog?.dismiss()
        }
    }
    private var initTime = 0L
    override fun initLayout() {
        super.initLayout()
        BaseApplication.sInstance.addActivity(activity)

        titleBar?.setOnTitleBarListener(this)
        // 初始化沉浸式状态栏
        if (isStatusBarEnabled) {
            statusBarConfig.init()
            // 设置标题栏沉浸
            if (titleBar != null) {
                ImmersionBar.setTitleBar(this, titleBar)
            }
        } else {
            setFitsSystemWindows()
        }

        //黑色标题栏
//        BarUtils.setStatusBarLightMode(this, isStatusBarDarkFont)
//        if (isStatus) {
//            BarUtils.setStatusBarColor(this, myContext.getColor(if (isStatusBarDarkFont) colorTitleBarBg else R.color.colorMatchDark))
//        } else {
//            BarUtils.setStatusBarColor(this, myContext.getColor(if (isStatusBarDarkFont)  R.color.black5 else colorTitleBarBg))
//
//        }
    }

    @CallSuper
    override fun initData() {
        rpcCallManager = RpcCallManager.RpcCallManagerImpl()
        initTime =  TimeUtils.getNowMills()
    }

    override fun <T> manageRpcCall(flowable: Flowable<T>, subscribe: ResourceSubscriber<T>) {
        rpcCallManager.manageRpcCall(flowable, subscribe)
    }

    /**
     * 是否使用沉浸式状态栏
     */
    protected open val isStatusBarEnabled: Boolean
        get() = true

    /**
     * 状态栏字体深色模式
     */
    protected open val isStatusBarDarkFont: Boolean
        get() = true

    /**
     * 状态栏字体深色模式
     */
    protected open val isStatus: Boolean
        get() = true

    /**
     * 状态栏神色字体下的背景色
     */
    protected open val colorTitleBarBg: Int
        @ColorRes
        get() = R.color.white


    /**
     * 初始化沉浸式状态栏
     */
    protected open fun createStatusBarConfig(): ImmersionBar {
        return ImmersionBar.with(this)
            // 默认状态栏字体颜色为黑色
            .statusBarDarkFont(isStatusBarDarkFont)
            // 指定导航栏背景颜色
            .navigationBarColor(R.color.white)
            // 状态栏字体和导航栏内容自动变色，必须指定状态栏颜色和导航栏颜色才可以自动变色
            .autoDarkModeEnable(true,0.2f)
    }

    /**
     * 获取状态栏沉浸的配置对象
     */
    val statusBarConfig: ImmersionBar
        get() {
            if (mImmersionBar == null) {
                mImmersionBar = createStatusBarConfig()
            }
            return mImmersionBar!!
        }

    /**
     * 设置标题栏的标题
     */
    override fun setTitle(@StringRes id: Int) {
        title = getString(id)
    }

    /**
     * 设置标题栏的标题
     */
    override fun setTitle(title: CharSequence?) {
        super<TitleBarAction>.setTitle(title)
        titleBar?.title = title
    }

    override val titleBar: TitleBar?
        get() {
            if (mTitleBar == null) {
                mTitleBar = obtainTitleBar(contentView)
            }
            return mTitleBar
        }

    override fun onLeftClick(titleBar: TitleBar) {
        onBackPressed()
    }

    override val onHttpListener: OnHttpListener<AppResponse<*>?>
        get() {
            return object : OnHttpListener<AppResponse<*>?> {

                override fun onStart(call: Call) {
                    showDialog()
                }

                override fun onSucceed(result: AppResponse<*>?) {
                    if (result is AppResponse<*> && "成功" != result.getResponseMessage()) {
                        toast(result.getResponseMessage())
                    }
                }

                override fun onFail(e: Exception?) {
                    toast(e?.message)
                }

                override fun onEnd(call: Call) {
                    hideDialog()
                }
            }
        }

    override fun startActivityForResult(intent: Intent, requestCode: Int, options: Bundle?) {
        super.startActivityForResult(intent, requestCode, options)
        overridePendingTransition(R.anim.right_in_activity, R.anim.right_out_activity)
    }

    override fun finish() {
        super.finish()
        overridePendingTransition(R.anim.left_in_activity, R.anim.left_out_activity)
    }

    override fun attachBaseContext(base: Context) {

        super.attachBaseContext(DisplayUtil.attachBaseContext(base, fontScale))

    }
    var fontScale = 1f

    override fun onKeyDown(keyCode: Int, event: KeyEvent): Boolean {
        //按后退返回
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ThreadUtils.runOnUiThreadDelayed({ finish() }, Constant.ActivityFinishDelay)
        }
        return super.onKeyDown(keyCode, event)
    }

    override fun getResources(): Resources {

        val resources = super.getResources()
        val config = resources.configuration
        return if(config.fontScale != fontScale) {
            config.fontScale = fontScale
            myContext.createConfigurationContext(config).resources
        } else {
            resources
        }

    }

    override fun onDestroy() {


        if (isShowDialog) {
            hideDialog()
        }
        mDialog = null
        super.onDestroy()
    }
}